package com.base.weeks.weekof59th;

/**
 * @ClassName MaxMatrixSum
 * @Description 5835. 最大方阵和
 * @Author li
 * Date 2021/8/22 10:34
 * Copyright
 **/
public class MaxMatrixSum {
    public long maxMatrixSum(int[][] matrix) {
        long sum = 0;
        // 最小绝对值数
        int minAbsolute = Integer.MAX_VALUE;
        int numOfNegative = 0;
        boolean hasZero = false;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                int tmp = matrix[i][j];
                if (hasZero) {
                    sum += Math.abs(tmp);
                } else {
                    if (tmp == 0) {
                        hasZero = true;
                        continue;
                    } else if (tmp < 0) {
                        numOfNegative++;
                        sum += Math.abs(tmp);
                    } else {
                        sum += tmp;
                    }
                    minAbsolute = Math.min(Math.abs(tmp),minAbsolute);
                }

            }
        }
        if (hasZero){
            return sum;
        }
        if (numOfNegative % 2 ==0){
            return sum;
        }
        return sum - 2L * minAbsolute;

    }
}
